/**
 * 处理登陆授权、地理位置授权的工具
 */

const store = require("./store")
const utils = require('../utils/util.js')
const {Toast, Dialog} = require("./modal")
const {
    gets,
    post,
} = require('./request.js');
const CONFIG = require('./config.js');

const FUN = {
    login: {
        isAuthLogin: function () {
            return !utils.isInvalid(store.getAuthorization());
        },
        checkLogin() {
            let userInfo = store.getUserInfo();
            if (utils.isInvalid(userInfo)) {
                Dialog.alert({
                    title: '友情提示',
                    message: '用户未授权/授权过期',
                    width: "250px",
                    confirmButtonColor: "#D2691E",
                    confirmButtonText: "去授权",
                    showCancelButton: true,
                    cancelButtonText: "取消",
                }).then(() => {
                    // on confirm
                    this.toLogin(() => {
                    })
                }).catch(() => {
                    // on cancel
                });
            }
        },
        toLogin(success) {
            wx.getUserProfile({
                lang: "zh_CN",
                desc: '获取您的昵称、头像信息～',
                success: (auth) => {
                    Toast.loading({
                        message: '加载中...',
                        mask: true,
                        forbidClick: false,
                        duration: 30000
                    });
                    console.log("授权成功", auth);
                    let userNewInfo = auth.userInfo;

                    // 将位置信息放到用户对象中
                    let userInfo = store.getUserInfo();
                    if (!utils.isInvalid(userInfo)) {
                        userNewInfo['provinceSure'] = userInfo.provinceSure
                        userNewInfo['citySure'] = userInfo.citySure
                    }
                    userNewInfo["schoolName"] = "";
                    store.saveUserInfo(userNewInfo);
                    // 小程序登陆 拿code换openid等信息
                    wx.login({
                        success: (login) => {
                            // 换openid
                            let code = login.code;
                            let info = JSON.parse(auth.rawData)

                            // 获取openId 和用户信息
                            post(false,true, CONFIG.paraOpenIdUrl, {
                                code: code,
                                encryptedData: auth.encryptedData,
                                iv: auth.iv,
                                nickName: info.nickName,
                                avatar: info.avatarUrl,
                                city: utils.isInvalid(userNewInfo['provinceSure']) ? auth.userInfo.city : userNewInfo['provinceSure'],
                            }, null, res => {
                                Toast.clear({})
                                if (res.R) {
                                    let userDb= res.data;
                                    for (const userDbKey in userDb) {
                                        userNewInfo[userDbKey]=userDb[userDbKey];
                                    }
                                    store.saveUserInfo(userNewInfo);
                                    success(userNewInfo);
                                }
                            });
                        }
                    })
                }
                , fail(res) {
                }
            });
        },

    },
    location: {
        // 是否已经授权获得了地理位置信息
        isAllowedLocation() {
            let userInfo = store.getUserInfo();
            if (!utils.isInvalid(userInfo) && !utils.isInvalid(userInfo["citySure"])) {
                return true;
            }
            return false;
        },
        getCity() {
            let userInfo = store.getUserInfo();
            if (!utils.isInvalid(userInfo) && !utils.isInvalid(userInfo["citySure"])) {
                return userInfo["citySure"];
            }
            return "";
        },
        checkLocation() {
            if (!this.isAllowedLocation()) {
                Dialog.alert({
                    title: '友情提示',
                    message: '无法获取当前位置，请手动开启授权',
                    width: "300px",
                    confirmButtonColor: "#D2691E",
                    confirmButtonText: "去授权",
                    showCancelButton: true,
                    cancelButtonText: "取消",
                }).then(() => {
                    wx.hideLoading()
                    wx.openSetting({
                        success(res) {
                            FUN.location.allowed(res => {
                            })
                        }
                    })
                }).catch(() => {
                    // on cancel
                    wx.hideLoading()
                });
                return;
            }
            this.allowed(res => {
            })
        },
        // 获取详细的地理位置信息 多个pois
        getDetailLocation(success) {
            let locations = store.getData("locations");
            store.removeData("locations");
            if (utils.isInvalid(locations)) {
                wx.getLocation({
                    type: 'wgs84',
                    altitude: true,
                    highAccuracyExpireTime: 10000,
                    success: (res) => {
                        console.log("获取地理位置信息", res)
                        // 纬度
                        let latitude = res.latitude;
                        // 经度
                        let longitude = res.longitude;

                        let locations = longitude + "," + latitude;
                        gets(true, CONFIG.parasLocationDetailUrl, {locations: locations}, null, res => {
                            if (res.R) {
                                console.log("解析地理具体位置", res.data)
                                success(res.data);
                            }
                        })
                    },
                    fail(res) {
                        console.log("拒绝获取地理位置")
                        Dialog.alert({
                            title: '友情提示',
                            message: '您已经拒绝授权位置信息，为了保证您能正常使用小程序，需要您的位置信息使用权限，请允许',
                            width: "250px",
                            confirmButtonColor: "#D2691E",
                            confirmButtonText: "授权位置信息",
                            showCancelButton: true,
                            cancelButtonText: "取消",
                        }).then(() => {
                            // on confirm
                            console.log("open location setting")
                            wx.openSetting({})
                        })
                            .catch(() => {
                                // on cancel
                            });
                    }
                })
                return;
            }

            gets(true, CONFIG.parasLocationDetailUrl, {locations: locations}, null, res => {
                if (res.R) {
                    console.log("解析地理具体位置", res.data)
                    success(res.data);
                }
            })

        },

        // 是否已经允许了授权
        allowed(callback) {
            wx.showLoading({
                title: '加载中',
                mask: true,
            })
            wx.getSetting({
                success: res => {
                    // 已授权
                    if (res.authSetting['scope.userLocation']) {
                        console.log('已授权定位')
                        if (!this.isAllowedLocation()) {
                            this.toReloadServer(res => {
                                wx.hideLoading();
                                if (!utils.isInvalid(callback)) {
                                    callback(true);
                                }
                            })
                            return;
                        }
                        wx.hideLoading();
                    } else if (utils.isInvalid(res.authSetting['scope.userLocation'])) {
                        console.log('初次授权')
                        if (!this.isAllowedLocation()) {
                            this.toReloadServer(res => {
                                wx.hideLoading();
                                if (!utils.isInvalid(callback)) {
                                    callback(true);
                                }
                            })
                            return;
                        }
                        wx.hideLoading();
                    } else if (res.authSetting['scope.userLocation'] === false) {
                        console.log('拒绝授权')
                        wx.hideLoading();
                        if (!utils.isInvalid(callback)) {
                            callback(false);
                        }
                        Dialog.alert({
                            title: '友情提示',
                            message: '您已经拒绝授权位置信息，为了保证您能正常使用小程序，需要您的位置信息使用权限，请允许',
                            width: "250px",
                            confirmButtonColor: "#D2691E",
                            confirmButtonText: "授权位置信息",
                            showCancelButton: true,
                            cancelButtonText: "取消",
                        }).then(() => {
                            // on confirm
                            console.log("open location setting")
                            wx.openSetting({})
                        })
                    }
                }, fail(res) {
                    console.log("fail!!!!")
                    callback(false);
                    wx.hideLoading();
                }
            })
        }
        // 授权地理位置，去服务器解析地理位置，并且将省市保存起来
        , toReloadServer(success) {
            wx.showLoading({
                title: '加载中',
                mask: true,
            })
            wx.getLocation({
                type: 'wgs84',
                altitude: true,
                highAccuracyExpireTime: 10000,
                success: (res) => {
                    console.log("获取地理位置信息", res)
                    // 纬度
                    let latitude = res.latitude;
                    // 经度
                    let longitude = res.longitude;


                    let locations = longitude + "," + latitude;

                    store.saveData("locations", locations);
                    gets(true, CONFIG.parasLocationUrl, {locations: locations}, null, res => {
                        wx.hideLoading();
                        if (res.R) {
                            let userInfo = store.getUserInfo();
                            if (utils.isInvalid(userInfo)) {
                                userInfo = {}
                                userInfo['schoolName'] = "-";
                            }
                            userInfo['provinceSure'] = res.data[0];
                            userInfo['citySure'] = ((res.data[1] == "[]") ? res.data[0] : res.data[1])
                            console.log("解析地理位置", res.data)
                            store.saveUserInfo(userInfo);
                            success(userInfo);
                            // 是否授权 更新地理位置信息
                            if (FUN.login.isAuthLogin()) {
                                post(false, CONFIG.updateLocationUrl, {city: userInfo['citySure']}, null, res => {
                                })
                            }
                        }
                    })
                },
                fail(res) {
                    wx.hideLoading()
                    console.log("已拒绝获取地理位置")
                    Dialog.alert({
                        title: '友情提示',
                        message: '无法获取当前位置，请手动开启授权',
                        width: "300px",
                        confirmButtonColor: "#D2691E",
                        confirmButtonText: "授权位置信息",
                        showCancelButton: true,
                        cancelButtonText: "取消",
                    }).then(() => {
                        // on confirm
                        console.log("open location setting")
                        wx.openSetting({
                            success(res) {
                                FUN.location.allowed(res => {
                                    if (res) {
                                        success(store.getUserInfo());
                                    }
                                })
                            }
                        })
                    }).catch(() => {
                        // on cancel
                    });
                }
            })
        },
        toAuthLocation(success) {
            this.toReloadServer(success);
        }
    }
}
module.exports = {
    LOGIN: FUN.login,
    LOCATION: FUN.location
}
